﻿using System;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace BlueSky.Web
{
    /// <summary>
    /// Controller factory class.
    /// </summary>
    public class ControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// Unity container.
        /// </summary>
        protected IUnityContainer _container;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="container">Unity container.</param>
        public ControllerFactory(IUnityContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            _container = container;
        }

        protected override IController GetControllerInstance(Type controllerType)
        {
            if (controllerType == null)
                throw new ArgumentNullException("controllerType");

            if (!typeof(IController).IsAssignableFrom(controllerType))
                throw new ArgumentException(string.Format("Type requested is not a controller: {0}", controllerType.Name), "controllerType");

            return _container.Resolve(controllerType) as IController;
        }

        public override void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null)            
                disposable.Dispose();
            
            _container.Teardown(controller);           
        }

    }
}
